from types import *
import pprint

class Gate:
	def __init__(self, env):
		self.env = Struct(env)
		self.headers = {'Content-type':'text/html; charset=utf-8'}
		self.length = 0
		self.code = 200
		self.message = 'OK'
		self.outBuffer = ''
#		self.headersSent = False
		self.outputStarted = False

	def setCode(self, code, message = 'OK'):
		self.code = code
		self.message = message

	def header(self, key, value):
		self.headers[key] = value

#	def done(self):
#		if not self.outputStarted:
#			if not self.headersSent:
#				self.sendHeaders()

	def sendHeaders(self):
#		if self.length > 0:
#			self.headers['Content-Length'] = self.length
#		self.env.out.write('\r\n'.join(key+': '+value for key, value in self.headers.items()) + '\r\n\r\n')
#		print 'HEADERS STATEEEEEEEEEEEEE: %s' % self.env._headersSent
#		print self.env
		if self.env._headersSent:
			raise Exception('Headers already sent')
		self.env._request.send_response(self.code, self.message)
		for key, value in self.headers.items():
			self.env._request.send_header(key, value)
		self.env._request.end_headers()
		self.env.set('_headersSent', True)
#		print self.env._headersSent

	def startOutput(self):
		if not self.env._headersSent:
			self.sendHeaders()

	def write(self, data):
#		self.env.out.write(data)
#		self.outputStarted = True
#		self.length = self.length+len(data)
#		self.outBuffer += data
		self.startOutput()
		self.env.out.write(str(data))

	def writen(self, data):
		self.write(str(data) + '\n')

	def dump(self, var, doReturn = False):
		if doReturn:
			return pprint.pformat(var, indent = 4)
		else:
			self.startOutput()
			pprint.pprint(var, indent = 4, stream = self.env.out)

#	def flush(self, data):
#		self.wasOutput = True
#		self.env.out.write('\n'.join(key+': '+value for key, value in self.headers.items()))
